package com.quectel.aiot.mapper;

import com.quectel.aiot.entity.Device;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface DeviceMapper {

    // ========== 修正 INSERT 语句 ==========
    // 将字段列表和值列表都统一为方案二的字段
    @Insert("INSERT INTO device (id, sn, manufacture_date, model, agent_id, name, activate, activate_time, out_time, ch_name, ch_gender, ch_date, product_key, device_key, device_desc, create_time, update_time, custom_fields, device_status, last_online_time, role_id, voice_id) " +
            "VALUES (#{id}, #{sn}, #{manufactureDate}, #{model}, #{agentId}, #{name}, #{activate}, #{activateTime}, #{outTime}, #{chName}, #{chGender}, #{chDate}, #{productKey}, #{deviceKey}, #{deviceDesc}, #{createTime}, #{updateTime}, #{customFields}, #{deviceStatus}, #{lastOnlineTime}, #{roleId}, #{voiceId})")
    void insert(Device device);

    // ========== 修正 UPDATE 语句 ==========
    // SET子句需要更新所有可变字段，包括新的 role_id 和 voice_id
    @Update("UPDATE device SET sn = #{sn}, manufacture_date = #{manufactureDate}, model = #{model}, agent_id = #{agentId}, name = #{name}, activate = #{activate}, activate_time = #{activateTime}, out_time = #{outTime}, ch_name = #{chName}, ch_gender = #{chGender}, ch_date = #{chDate}, device_desc = #{deviceDesc}, " +
            "device_status = #{deviceStatus}, last_online_time = #{lastOnlineTime}, update_time = #{updateTime}, custom_fields = #{customFields}, " +
            "role_id = #{roleId}, voice_id = #{voiceId} " + // <-- 在这里添加对新字段的更新
            "WHERE product_key = #{productKey} AND device_key = #{deviceKey}")
    void update(Device device);

    // ========== 新增一个专门用于切换角色的、更高效的方法 ==========
    @Update("UPDATE device SET role_id = #{roleId}, voice_id = #{voiceId} " +
            "WHERE product_key = #{pk} AND device_key = #{dk}")
    int updateCurrentRoleAndVoice(@Param("pk") String pk, @Param("dk") String dk,
                                  @Param("roleId") Long roleId, @Param("voiceId") Long voiceId);


    // ========== 以下 SELECT 方法无需修改 SQL ==========
    // "SELECT *" 会自动包含新字段 role_id 和 voice_id。
    // **前提是您的 Device.java 实体类必须已添加 roleId 和 voiceId 字段及其getter/setter。**

    @Select("SELECT * FROM device WHERE product_key = #{productKey} AND device_key = #{deviceKey}")
    Device findByProductKeyAndDeviceKey(@Param("productKey") String productKey, @Param("deviceKey") String deviceKey);

    @Select("SELECT * FROM device WHERE product_key = #{productKey}")
    List<Device> findByProductKey(String productKey);

    @Select("SELECT * FROM device")
    List<Device> findAll();

    @Select("SELECT * FROM device WHERE id = #{deviceId}")
    Device findById(String deviceId);

    // ========== DELETE 方法无需修改 ==========
    @Delete("DELETE FROM device WHERE id = #{deviceId}")
    void deleteById(String deviceId);
}